<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" width="600px">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form';
import { categoryFormSchema } from './table.data';
import { saveOrUpdateCategory } from './table.api';

const emit = defineEmits(['success', 'register']);
const tenantId = ref(null)
const isUpdate = ref(true);

const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  schemas: categoryFormSchema,
  showActionButtonGroup: false,
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 18 },
  },
});

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  await resetFields();
  setModalProps({ confirmLoading: false, height: 200, draggable: false, canFullscreen: false});
  isUpdate.value = !!data?.isUpdate;
  tenantId.value = data?.tenantId;
  if (unref(isUpdate)) {
    await setFieldsValue({
      ...data.record,
    });
  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增类型' : '编辑类型'));

async function handleSubmit() {
  try {
    const values = await validate();
    values.tenantId = tenantId.value
    setModalProps({ confirmLoading: true });
    await saveOrUpdateCategory(values, isUpdate.value);
    closeModal();
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>
